/**
 * Created by Ng on 2023/11/13
 */

import { useUserStore } from '@/stores/user'
import { setStorage, getStorage, clearStorage } from '@/utils'

// token key
const TOKEN = 'ACCESS_TOKEN'
// 时长 15 天
const DURATION = 1000 * 60 * 60 * 24 * 15
// 用户登录方式
const ACCESS_LOGINMETHOD = 'ACCESS_LOGINMETHOD'

/**
 * @description 是否登录
 * @returns {Boolean | Null}
 */
export function isLogin() {
  if (!window.localStorage) return
  return !!localStorage.getItem(TOKEN)
}

/**
 * @description 获取用户 TOKEN
 * @returns {Object | Null}
 */
export function getToken() {
  if (!window.localStorage) return
  let value = localStorage.getItem(TOKEN)
  let userStore = useUserStore()
  try {
    let object = JSON.parse(value)
    let { token, time, expires } = object
    if (!expires) {
      return object
    }
    if (expires > new Date().getTime()) {
      return object
    }
    userStore.clear()
    return null
  } catch (error) {
    userStore.clear()
    return null
  }
}

/**
 * @description 设置用户 TOKEN
 * @param {String} token
 * @param {Boolean} isExpires
 * @returns {Boolean | Null}
 */
export function setToken(token, isExpires = false) {
  let object = JSON.stringify({
    token,
    time: Date.now(),
    expires: isExpires ? new Date().getTime() + DURATION : null
  })
  if (!window.localStorage) return
  return localStorage.setItem(TOKEN, object)
}

/**
 * @description 清除用户 TOKEN
 * @returns {Boolean | Null}
 */
export function clearToken() {
  if (!window.localStorage) return
  return localStorage.removeItem(TOKEN)
}

/**
 * @description 指定时长刷新
 */
export function refreshAccessToken() {
  let tokenItem = getToken()
  if (!tokenItem) return
  let { time, expires } = tokenItem
  if (!expires) return
  if (new Date().getTime() - time <= DURATION) return
  try {
    // 重新获取 token 并保存
    let userStore = useUserStore()
    userStore.netRefreshAccessToken()
  } catch (error) {
    console.error(error)
  }
}


/**
 * @description 获取用户登录方式
 * @param {*} value 值
 */
export function setLoginMethod(value) {
  setStorage(ACCESS_LOGINMETHOD, value)
}

/**
 * @description 设置用户登录方式
 * @returns {String}
 */
export function getLoginMethod() {
  return getStorage(ACCESS_LOGINMETHOD)
}

/**
 * @description 清除登录方式
 */
export function clearLoginMethod() {
  clearStorage(ACCESS_LOGINMETHOD)
}
